<?php

/**
 * Author: xx.com
 * Date: 2015-09-09
 */

namespace Home\Logic;

use Think\Model\RelationModel;
/**
 * 购物车 逻辑定义
 * Class CatsLogic
 * @package Home\Logic
 */
class CartLogic extends RelationModel
{


    /**
     * 加入购物车方法
     * @param type $goods_id  商品id
     * @param type $goods_num   商品数量
     * @param type $goods_spec  选择规格 
     * @param type $user_id 用户id
     */
    function addCart($goods_id, $goods_num, $goods_spec = '', $session_id, $user_id = 0, $shop_id = 0)
    {
        $goods = M('Goods')->where(array('goods_id' => $goods_id, 'is_on_sale' => 1))->find(); // 找出这个商品
        // var_dump($goods);die;
        if (!$goods) {
            return array('status' => -6, 'msg' => '商品已下架', 'result' => '');
        }

        $shop_goods = M('shop_goods')->alias('shop_goods')
            ->field('shop_goods.*')
            ->join('ln_shop as shop on shop_goods.shop_id = shop.id', 'left')
            ->where(array(
                'shop_goods.goods_id'=>$goods_id,
                'shop_goods.shop_on_sale'=>1,
                'shop_goods.store_count'=>array('gt', 0),
                'shop.is_open'=>1
            ))
            ->select();
        if(!$shop_goods){
            return array('status'=>-1, 'msg'=>'暂无配送渠道', 'result'=>'');
        }
        $real_store_count = 0;
        foreach($shop_goods as $val){
            $real_store_count += $val['store_count'];
        }
        //$specGoodsPriceList = M('SpecGoodsPrice')->where("goods_id = $goods_id")->getField("key,key_name,price,store_count,sku"); // 获取商品对应的规格价钱 库存 条码
        $where = " session_id = '$session_id' ";
        $user_id = $user_id ? $user_id : 0;
        /*$shop_id = $shop_id ? $shop_id : 0;
        if ($shop_id) {
            $where .= "  or shop_id= $shop_id ";
        }*/
        if ($user_id) {
            $where .= "  or user_id= $user_id ";
        }
        // var_dump($specGoodsPriceList);die;
        $catr_count = M('Cart')->where($where)->count(); // 查找购物车商品总数量
        if ($catr_count >= 100)
            return array('status' => -9, 'msg' => '购物车最多只能放100种商品', 'result' => '');
            // if (!empty($specGoodsPriceList) && empty($goods_spec)) // 有商品规格 但是前台没有传递过来
            //     return array('status' => -1, 'msg' => '必须传递商品规格', 'result' => '');
        if ($goods_num <= 0)
            return array('status' => -2, 'msg' => '购买商品数量不能为0', 'result' => '');
            // if (empty($goods))
            //     return array('status' => -3, 'msg' => '购买商品不存在', 'result' => '');
        /*if (($goods['store_count'] < intval($goods_num)))*/
        if (($real_store_count < intval($goods_num)))
            return array('status' => -4, 'msg' => '商品库存不足', 'result' => '');
        /*if (!empty($specGoodsPriceList)) // 有选择商品规格
        {
            if (empty($goods_spec)) {
                return array('status' => -3, 'msg' => '商品规格未选择', 'result' => '');
            }

            $spec_key = $goods_spec;
            // foreach ($specGoodsPriceList as $key => $value) {
            //     $spec_key = $value['key'];
            // }
            if ($specGoodsPriceList[$spec_key]['store_count'] < intval($goods_num)) {
                return array('status' => -4, 'msg' => '商品库存不足', 'result' => '');
            }
            $spec_price = $specGoodsPriceList[$spec_key]['price']; // 获取规格指定的价格
        }*/

        $where = " goods_id = $goods_id and status = 1 "; // 查询购物车是否已经存在这商品
        if ($user_id > 0)
            $where .= " and user_id = {$user_id} ";
        else
            $where .= " and session_id = '$session_id' ";

        $catr_goods = M('Cart')->where($where)->find(); // 查找购物车是否已经存在该商品
            // var_dump("spec_price",$spec_price);
            // var_dump("shop_price",$goods['shop_price']);die;
        $shop_price = $goods['shop_price']; // 如果商品规格没有指定价格则用商品原始价格
        $price = $shop_price;

            // var_dump("price",$price);
            // var_dump("shop_price",$shop_price);
            // die;
            
            // 商品参与促销
        if ($goods['prom_type'] == 3 && $goods['prom_id']) {
            $prom = get_goods_promotion($goods_id, $user_id, $price);
            $price = $prom['price'];
            $goods['prom_type'] = $prom['prom_type'];
            $goods['prom_id'] = $prom['prom_id'];
            $goods['prom_price'] = $prom['prom_price'];
        } elseif ($goods['prom_type'] == 2 && $goods['prom_id']) {
                //参与团购 的不进入购物车，直接以商店价进行结算
                // $prom = get_goods_group($goods_id);
                // $price = $prom['price'];
                // $goods['prom_type'] = $prom['prom_type'];
                // $goods['prom_id'] = $prom['prom_id'];
                // $goods['prom_price'] = $prom['price'];
        } elseif ($goods['prom_type'] == 1 && $goods['prom_id']) {
            $prom = get_goods_kill($goods_id);
            $price = $prom['price'];
            $goods['prom_type'] = $prom['prom_type'];
            $goods['prom_id'] = $prom['prom_id'];
            $goods['prom_price'] = $price;
        }

            // var_dump($goods);
            // var_dump("price",$price);die;


        $data = array(
            'user_id' => $user_id,   // 用户id
            'shop_id' => $shop_id,  //商铺id
            'session_id' => $session_id,   // sessionid
            'goods_id' => $goods_id,   // 商品id
            'goods_sn' => $goods['goods_sn'],   // 商品货号
            'goods_name' => $goods['goods_name'],   // 商品名称
            'market_price' => intval($goods['market_price'] * 100) / 100,   // 市场价
            'goods_price' => intval($price * 100) / 100,  // 购买价
            'member_goods_price' => intval($price * 100) / 100,  // 会员折扣价 默认为 购买价
            'goods_num' => $goods_num, // 购买数量
            'spec_key' => "", // 规格key
            'spec_key_name' => "", // 规格 key_name
            'sku' => "", // 商品条形码
            'add_time' => time(), // 加入购物车时间
            'prom_type' => $goods['prom_type'],   // 0 普通订单,1 限时抢购, 2 团购 , 3 促销优惠
            'prom_id' => $goods['prom_id'],   // 活动id
            'prom_price' => intval($shop_price * 100) / 100,       //加入购物车时商品原价格
        );
//             var_dump("price",$price);
// var_dump($data);die;
            // 如果商品购物车已经存在
        if ($catr_goods) {
                //当商品参与限时抢购
            if ($goods['prom_type'] == 1 && $goods['prom_id']) {
                $num = M('flash_sale as fs')->field('c.goods_num,fs.goods_num as buy_num,fs.buy_limit')->join('ln_cart as c on c.goods_id=fs.goods_id')->where("fs.goods_id = $goods_id and c.user_id=$user_id")->select();
                $goods_buy_num = M('cart')->field('sum(goods_num)')->where("goods_id=$goods_id")->group('prom_type=1')->select();
                $goods_num = $num[0]['goods_num'];
                $buy_num = $num[0]['buy_num'];
                $buy_limit = $num[0]['buy_limit'];
                if ($goods_num >= $buy_limit) {
                    return array('status' => -1, 'msg' => "每人只限" . $buy_limit . "件", 'result' => '');
                }
                if ($goods_buy_num > $buy_num) {
                    return array('status' => -1, 'msg' => '购买数量超过限购数量', 'result' => '');
                }
            }
                //当商品参与团购
                // if ($goods['prom_type'] == 2 && $goods['prom_id']) {
                //     $num = M('group_buy as fs')->field('c.goods_num,fs.goods_num as buy_num,fs.virtual_num')->join('ln_cart as c on c.goods_id=fs.goods_id')->where("fs.goods_id = $goods_id and c.user_id=$user_id")->select();
                //     $goods_buy_num = M('cart')->field('sum(goods_num)')->where("goods_id=$goods_id")->group('prom_type=2')->select();
                //     $goods_num = $num[0]['goods_num'];
                //     $buy_num = $num[0]['buy_num'];
                //     $virtual_num = $num[0]['virtual_num'];
                //     if ($goods_buy_num>1) {
                //        return array('status'=>-1,'msg'=>"每人只限1件",'result'=>'');
                //     }
                    
                // }
                
                // 如果购物车的已有数量加上 这次要购买的数量  大于  库存输  则不再增加数量
            /*if (($catr_goods['goods_num'] + $goods_num) > $goods['store_count']) */
            if (($catr_goods['goods_num'] + $goods_num) > $real_store_count)
            {
                return array('status' => -1, 'msg' => '购买数量超过渠道库存总量', 'result' => '');
            }

            $update_cart = array(
                'goods_num' => ($catr_goods['goods_num'] + $goods_num),     //数量相加
                'prom_price' => intval($shop_price * 100) / 100,                                //更新加入购物车时商品原价格
                'goods_price' => intval($price * 100) / 100,                                //更新购买价
                'member_goods_price' => intval($price * 100) / 100,                             //更新会员折扣价 默认为 购买价
                'prom_type' => $goods['prom_type'],   // 0 普通订单,1 限时抢购, 2 团购 , 3 促销优惠
                'prom_id' => $goods['prom_id'],
            );
            $result = M('Cart')->where("id =" . $catr_goods['id'])->save($update_cart); // 数量相加
            if ($result !== false) {
                $cart_count = cart_goods_num($user_id, $session_id); // 查找购物车数量
                setcookie('cn', $cart_count, null, '/');
                return array('status' => 1, 'msg' => '成功加入购物车', 'result' => $cart_count);

            }

        } else {
            $insert_id = M('Cart')->data($data)->add();
            if ($insert_id) {
                $cart_count = cart_goods_num($user_id, $session_id); // 查找购物车数量
                setcookie('cn', $cart_count, null, '/');
                return array('status' => 1, 'msg' => '成功加入购物车', 'result' => $cart_count);
            }
        }
        $cart_count = cart_goods_num($user_id, $session_id); // 查找购物车数量
        return array('status' => -5, 'msg' => '加入购物车失败', 'result' => $cart_count);
    }


    /**
     * 购物车列表(增加运费显示)
     * @param type $user   用户
     * @param type $session_id  session_id
     * @param type $selected  是否被用户勾选中的 0 为全部 1为选中  一般没有查询不选中的商品情况
     * @param mode 0  返回数组形式  1 直接返回result
     */
    function cartList($user = array(), $session_id = '', $selected = 0, $mode = 0)
    {

        /*****新代码*****************/ 
        // var_dump($user);die;
        // 按店铺进行隔离
        $where['c.status'] = 1;
        if ($user && $user['user_id']) {
            $where['c.user_id'] = $user['user_id'];
        } else {
            $where['c.session_id'] = $session_id;
            $user['user_id'] = 0;
        }


        //$subCartList = M('Cart as c')
            //->field('DISTINCT shop_id')
        //    ->where($where)
        //    ->select();
       // print_r($subCartList);
        // var_dump($subCartList);die;

        // if (empty($subCartList)) {
        //     #空购物车

        // }

        $total_buy_number = 0; // 购买的总数量
        $total_amount = 0;  // 商品总金额
        $real_pay_amount = 0;  // 商品需要支付的总金额
        $express_amount = 0; // 总运费
        $all_pay_point = 0; // 总共需要扣除的积分    
        $total_cut_fee = 0;
        $total_market_cut_fee = 0;

        $point_ex_rate = tpCache('shopping.point_rate');//积分兑换比例

        $orderGoodsModel = M('order_goods');
        $specItemModel = M('spec_item');
        $cartModel = M('Cart');
        $shopModel = M('Shop');
        $goodsModel = M('Goods');

        //$f_list = [];
        //foreach ($subCartList as $k => &$v) {

            /*$shop_info = $shopModel->where([
                "id" => $v['shop_id']
            ])->field("id,shop_name,shop_head_img")->cache(300)->find();
            if (!$shop_info) {
                $v['shop_name'] = "";
                $v['shop_head_img'] = "";
                $v['cart_list'] = [];
                continue;
            }*/

            //$v['shop_name'] = $shop_info['shop_name'] ? $shop_info['shop_name'] : "";
            //$v['shop_head_img'] = $shop_info['shop_head_img'] ? parseMediaUrl($shop_info['shop_head_img']) : "";
            //$v['selected'] = 1;

            //$where['c.shop_id'] = $v['shop_id'];
            if ($selected) {
                $where['c.selected'] = 1;
            }
            $shopGoodsList = $cartModel->where($where)->alias('c')
                ->join('ln_goods as g on g.goods_id=c.goods_id')
                ->field('c.id,c.user_id,c.session_id,c.member_goods_price,c.bar_code,c.sku,g.goods_remark,g.goods_id,
                c.goods_name,c.goods_num,c.shop_id,c.market_price,c.goods_price,c.spec_key,c.spec_key_name,c.selected,
                c.add_time,c.prom_id,c.prom_type,c.prom_price,c.status,g.is_free_shipping,g.exchange_integral,g.original_img,
                g.is_city,g.shop_goods_type')
                ->select();

            #店内计价
            // $price_info = calculate_price(0, 0, 0, $user_id, $v['cart_list'], 0, 0, 0, 0, 0);

            //$v['cartList'] = [];//商品
            //$v['total_price'] = [];// 总价
            // $v['all_pay_point'] = 0;//总需要积分
            // $v['integral_money'] = 0;//积分可抵扣金额
            // $v['available_points'] = 0;//可用积分

            $total_price = 0;//应付价
            $goods_price = 0;//标价
            $weight = 0;//总重量
            $anum = 0;
            $cut_fee = 0;
            $market_cut_fee = 0;
            $exchange_integral = 0;

            foreach ($shopGoodsList as $key => $vv) {
                $goods = $goodsModel->where(array('goods_id' => $vv['goods_id'], 'is_on_sale' => 1))->find();

                if (!$goods) {
                    $data['status'] = 0;
                    $data['selected'] = 0;
                    M('Cart')->where(array('id' => $vv['id']))->save([
                        "status" => 0,
                        "selected" => 0,
                    ]);

                    continue;
                }

                $shopGoodsList[$key]['original_img'] = parseMediaUrl($vv['original_img']);

                //if (0 == $vv['selected']) {
                //    $v['selected'] = 0;
                //}


                if (!empty($vv['spec_key'])) // 有商品规格
                {
                    $specGoodsPrice = M('SpecGoodsPrice')
                        ->field("key,key_name,price,store_count")
                        ->where(array('goods_id' => $goods['goods_id'], 'key' => $vv['spec_key']))
                        ->find();       // 获取商品对应的规格价钱 库存

                    $store_count = $specGoodsPrice['store_count']; //购买数量最大为库存
                    $spec_price = $specGoodsPrice['price']; // 获取规格指定的价格
                } else {
                    $store_count = $goods['store_count']; //购买数量最大为库存
                    $spec_price = $goods['shop_price']; // 如果商品规格没有指定价格则用商品原始价格
                }
                // var_dump($goods);die;
                $prom_price = $spec_price;

                // 商品的单价
                $promPrice = calcGoodsPrice($goods, $spec_price, $vv['spec_key']);
                $price = $promPrice['price'];

                if ($promPrice['is_prom']) {
                    $data['goods_price'] = $price;          // 购买价
                    $data['member_goods_price'] = $price;  // 会员折扣价 默认为 购买价
                    $data['prom_type'] = $goods['prom_type'];    // 0 普通订单, 3 促销优惠
                    $data['prom_id'] = $goods['prom_id'];      // 活动id
                    $data['prom_price'] = $price;  // 活动价
                } else {
                    $data['goods_price'] = $price;          // 购买价
                    $data['member_goods_price'] = $price;  // 会员折扣价 默认为 购买价
                    $data['prom_type'] = 0;    // 0 普通订单, 3 促销优惠
                    $data['prom_id'] = 0;      // 活动id
                    $data['prom_price'] = $price;  // 活动价
                }

                // if ($goods['prom_type'] == 3 && $goods['prom_id']) {
                //     // 商品参与促销
                //     $prom = get_goods_promotion($goods['goods_id'], $user['user_id'], $spec_price);
                //     $data['goods_price'] = $prom['goods_price'];          // 购买价
                //     $data['member_goods_price'] = $prom['price'];  // 会员折扣价 默认为 购买价
                //     $data['prom_type'] = $prom['prom_type'];    // 0 普通订单, 3 促销优惠
                //     $data['prom_id'] = $prom['prom_id'];      // 活动id
                //     $data['prom_price'] = $spec_price;  //加入购物车时商品原价格

                // } elseif ($goods['prom_type'] == 1 && $goods['prom_id']) {
                //     // 商品参与、限时秒杀
                //     $prom = get_goods_kill($goods['goods_id']);
                //     var_dump($prom);die;
                //     $data['goods_price'] = $prom['goods_price'];          // 购买价
                //     $data['member_goods_price'] = $prom['price'];  // 会员折扣价 默认为 购买价
                //     $data['prom_type'] = $prom['prom_type'];    // 0 普通订单, 3 促销优惠
                //     $data['prom_id'] = $prom['prom_id'];      // 活动id
                //     $data['prom_price'] = $spec_price;  //加入购物车时商品原价格
                // } else if ($goods['prom_type'] == 2 && $goods['prom_id']) {
                //     // //商品参与团购
                //     // $prom = get_goods_group($goods['goods_id']);
                //     // $data['goods_price'] = $prom['goods_price'];          // 购买价
                //     // $data['member_goods_price'] = $prom['price'];  // 会员折扣价 默认为 购买价
                //     // $data['prom_type'] = $prom['prom_type'];    // 0 普通订单, 3 促销优惠
                //     // $data['prom_id']   = $prom['prom_id'];      // 活动id
                //     // $data['prom_price'] = $spec_price;  //加入购物车时商品原价格
                //     $user['discount'] = (empty($user[discount])) ? 1 : $user['discount'];
                //     $data['goods_price'] = $spec_price;
                //     $data['member_goods_price'] = bcmul($spec_price, bcdiv($user['discount'], 1, 2), 2);
                //     $data['prom_type'] = 0;    // 0 普通订单, 3 促销优惠
                //     $data['prom_id'] = 0;      // 活动id
                //     $data['prom_price'] = $spec_price;  //加入购物车时商品原价格
                // } else {
                //     $user['discount'] = (empty($user[discount])) ? 1 : $user['discount'];
                //     $data['goods_price'] = $spec_price;
                //     $data['member_goods_price'] = bcmul($spec_price, bcdiv($user['discount'], 1, 2), 2);
                //     $data['prom_type'] = 0;    // 0 普通订单, 3 促销优惠
                //     $data['prom_id'] = 0;      // 活动id
                //     $data['prom_price'] = $spec_price;  //加入购物车时商品原价格
                // }

                $data['goods_sn'] = $goods['goods_sn'];   // 商品货号
                $data['goods_name'] = $goods['goods_name'];   // 商品名称
                $data['market_price'] = $goods['market_price'];   // 市场价

                M('Cart')->where(array('id' => $vv['id']))->save($data);
                // var_dump($user,$data,$vv);exit;
                $vv['goods_price'] = $price;//显示出去的
                $vv['member_goods_price'] = $data['member_goods_price'] > 0 ? $data['member_goods_price'] : $vv['goods_price'];
               
            //    var_dump($vv);die;
                //列表中有效商品
                $val_true = $vv;

                $member_goods_price = $vv['member_goods_price'];
                $val_true['goods_price'] = $vv['goods_price'];          // 购买价
                $val_true['member_goods_price'] = $vv['member_goods_price'];  // 购买价

                $val_true['goods_fee'] = bcmul($vv['goods_num'], $vv['member_goods_price'], 2);   //单件商品总价
                $val_true['store_count'] = $store_count; // 最多可购买的库存数量 
                $val_true['status'] = $vv['goods_num'] <= $store_count ? 1 : 0;
                $cartList_true[] = $val_true;

                //$v['cartList'][] = $vv;

                // 如果要求只计算购物车选中商品的价格 和数量  并且  当前商品没选择 则跳过
                // if ($selected == 1 && $vv['selected'] == 0) {
                if ($vv['selected'] == 0) {
                    continue;
                }

                $anum += $vv['goods_num'];     //商品总数量

                if ($mode == 1) {
                    $cut_fee += bcmul($vv['goods_num'], bcsub($spec_price, $vv['member_goods_price'], 2), 2);
                }

                $goods_price += bcmul($vv['goods_num'], $vv['goods_price'], 2);

                $market_cut_fee += bcmul($vv['goods_num'], bcsub($goods['market_price'], $vv['member_goods_price'], 2), 2);

                $total_price += bcmul($vv['goods_num'], $vv['member_goods_price'], 2);

                // if($order_status){
                //     $order_status = $val_true['status'];
                // }
                if (!$goods['is_free_shipping']) {
                    $weight += $goods['weight'];
                }


                $exchange_integral += $goods['exchange_integral'] * $vv['goods_num'];
            }

            //$v['all_pay_point'] = $exchange_integral;//总需要积分
            //$v['integral_money'] = $exchange_integral / $point_ex_rate;//积分可抵扣金额
            //$v['available_points'] = 0;//可用积分
// p($v['shop_id']);die;
            /*$v['total_price'] = array(
                'total_fee' => $total_price,
                'post_fee' => \Common\Logic\FeeLogic::getPostFee($v['shop_id'], $weight, $total_price),
                'cut_fee' => $cut_fee,
                'num' => $anum,
                'market_cut_fee' => $market_cut_fee
            ); */// 店铺总计

            #对选中项 计算价格并计入总数

            $total_buy_number += $anum; // 购买的总数量
            $total_amount = bcadd($total_amount, $goods_price, 2);  // 商品标价总金额
            $real_pay_amount = bcadd($real_pay_amount, $total_price, 2);  // 商品需要支付的总金额
            //$express_amount = bcadd($express_amount, $v['total_price']['post_fee']); // 总运费
            $all_pay_point += $exchange_integral; // 总共需要扣除的积分    
            $total_cut_fee = bcadd($total_cut_fee, $cut_fee, 2);
            $total_market_cut_fee = bcadd($total_market_cut_fee, $market_cut_fee, 2);

            //if (isset($v['cartList']) && !empty($v['cartList'])) {
            //    $f_list[] = $v;
            //}
        //}

        $total_price_arr = array(
            'total_fee' => $real_pay_amount,
            'cut_fee' => $total_cut_fee,
            //'post_fee' => $express_amount,
            'num' => $total_buy_number,
            'market_cut_fee' => $total_market_cut_fee
        ); // 总计


        setcookie('cn', $total_buy_number, null, '/');

        //判断允许的最大积分 //商品总价最高可使用抵扣积分
        $order_amount_point = intval($total_price * $point_ex_rate);
        $all_pay_point = $all_pay_point > $order_amount_point ? $order_amount_point : $all_pay_point;  //订单最高允许使用积分
        #账户可用积分

        if ($user && $user['user_id']) {
            $user = M('users')->where([
                "user_id" => $user['user_id']
            ])->field("user_id,pay_points")->find();
        }

        $result = [
            "cartList" => $shopGoodsList,
            "total_price" => $total_price_arr,
            "all_pay_point" => $all_pay_point,
            "integral_money" => $all_pay_point / $point_ex_rate,
            "available_points" => isset($user['pay_points']) ? $user['pay_points'] : 0,
        ];

        if ($mode == 1) return $result;

        return array('status' => 1, 'msg' => '获取成功', 'result' => $result);
    }

    /**
     * 计算商品的的运费 
     * @param type $shipping_code 物流 编号
     * @param type $province  省份
     * @param type $city     市
     * @param type $district  区
     * @return int
     */
    function cart_freight2($weight, $province, $city, $district)
    {
        if ($weight == 0) return 0; // 商品没有重量
        $shipping_code = tpCache('shopping.default_shipping');
        if ($shipping_code == '') return 0;
    // 先根据 镇 县 区找 shipping_area_id
        $shipping_area_id = M('AreaRegion')->where("shipping_area_id in (select shipping_area_id from  " . C('DB_PREFIX') . "shipping_area where shipping_code = '$shipping_code') and region_id = {$district}")->getField('shipping_area_id');

    // 先根据市区找 shipping_area_id
        if ($shipping_area_id == false)
            $shipping_area_id = M('AreaRegion')->where("shipping_area_id in (select shipping_area_id from  " . C('DB_PREFIX') . "shipping_area where shipping_code = '$shipping_code') and region_id = {$city}")->getField('shipping_area_id');

    // 市区找不到 根据省份找shipping_area_id
        if ($shipping_area_id == false)
            $shipping_area_id = M('AreaRegion')->where("shipping_area_id in (select shipping_area_id from  " . C('DB_PREFIX') . "shipping_area where shipping_code = '$shipping_code') and region_id = {$province}")->getField('shipping_area_id');

    // 省份找不到 找默认配置全国的物流费
        if ($shipping_area_id == false) {
        // 如果市和省份都没查到, 就查询 tp_shipping_area 表 is_default = 1 的  表示全国的  select * from `tp_plugin`  select * from  `tp_shipping_area` select * from  `tp_area_region`
            $shipping_area_id = M("ShippingArea")->where("shipping_code = '$shipping_code' and is_default = 1")->getField('shipping_area_id');
        }
        if ($shipping_area_id == false)
            return 0;
    /// 找到了 shipping_area_id  找config
        $shipping_config = M('ShippingArea')->where("shipping_area_id = $shipping_area_id")->getField('config');
        $shipping_config = unserialize($shipping_config);
        $shipping_config['money'] = $shipping_config['money'] ? $shipping_config['money'] : 0;

    // 1000 克以内的 只算个首重费
        if ($weight < $shipping_config['first_weight']) {
            return $shipping_config['money'];
        }
    // 超过 1000 克的计算方法
        $weight = $weight - $shipping_config['first_weight']; // 续重
        $weight = ceil($weight / $shipping_config['second_weight']); // 续重不够取整
        $freight = $shipping_config['money'] + $weight * $shipping_config['add_money']; // 首重 + 续重 * 续重费

        return $freight;
    }

    /**
     * 获取用户可以使用的优惠券
     * @param type $user_id  用户id 
     * @param type $coupon_id 优惠券id
     * $mode 0  返回数组形式  1 直接返回result
     */
    public function getCouponMoney($user_id, $coupon_id, $mode)
    {
        $couponlist = M('CouponList')->where("uid = $user_id and id = $coupon_id")->find(); // 获取用户的优惠券
        if (empty($couponlist)) {
            if ($mode == 1) return 0;
            return array('status' => 1, 'msg' => '', 'result' => 0);
        }

        $coupon = M('Coupon')->where("id = {$couponlist['cid']}")->find(); // 获取 优惠券类型表
        $coupon['money'] = $coupon['money'] ? $coupon['money'] : 0;

        if ($mode == 1) return $coupon['money'];
        return array('status' => 1, 'msg' => '', 'result' => $coupon['money']);
    }

    /**
     * 根据优惠券代码获取优惠券金额
     * @param type $couponCode 优惠券代码
     * @param type $order_momey Description 订单金额
     * return -1 优惠券不存在 -2 优惠券已过期 -3 订单金额没达到使用券条件
     */
    public function getCouponMoneyByCode($couponCode, $order_momey)
    {
        $couponlist = M('CouponList')->where("code = '$couponCode'")->find(); // 获取用户的优惠券
        if (empty($couponlist))
            return array('status' => -9, 'msg' => '优惠券码不存在', 'result' => '');
        $coupon = M('Coupon')->where("id = {$couponlist['cid']}")->find(); // 获取优惠券类型表
        if (time() > $coupon['use_end_time'])
            return array('status' => -10, 'msg' => '优惠券已经过期', 'result' => '');
        if ($order_momey < $coupon['condition'])
            return array('status' => -11, 'msg' => '金额没达到优惠券使用条件', 'result' => '');
        if ($couponlist['order_id'] > 0)
            return array('status' => -12, 'msg' => '优惠券已被使用', 'result' => '');

        return array('status' => 1, 'msg' => '', 'result' => $coupon['money']);
    }

    /**
     *  立即购买时候添加一个订单
     * @param type $user_id  用户id     
     * @param type $address_id 地址id
     * @param type $shipping_code 物流编号
     * @param type $invoice_title 发票
     * @param type $coupon_id 优惠券id
     * @param type $goods_spec guige
     * @return type $order_id 返回新增的订单id
     */
    public function addOrder($user_id, $address_id, $invoice_title, $coupon_id = 0, $goods_spec = null, $user_note, $shop_id, $goods_id, $goods_num, $pay_points = 0)
    {
        // var_dump( $goods_id,$goods_num, $user_id,$goods_spec,0,$pay_points );
        if (empty($goods_id)) {
            return [
                "status" => -1,
                "msg" => "商品id无效",
                "result" => ""
            ];
        }

        if (empty($goods_num)) {
            return [
                "status" => -1,
                "msg" => "商品数量无效",
                "result" => ""
            ];
        }
        // 仿制灌水 1天只能下 50 单  // select * from `tp_order` where user_id = 1  and order_sn like '20151217%' 
        $order_count = M('Order')->where("user_id= $user_id and order_sn like '" . S . date('Ymd') . "%'")->count(); // 查找购物车商品总数量
        if ($order_count >= 100)
            return array('status' => -9, 'msg' => '一天只能下100个订单', 'result' => '');

        //$calc_result = calculate_price(1, $goods_id, $goods_num, $user_id, $goods_spec, 0, $pay_points,0,$coupon_id);
        $goodsModel = M('goods');
        $fields = array('goods_id','goods_name','goods_sn', 'weight','store_count','shop_price','market_price','is_free_shipping','exchange_integral','prom_type','prom_id',
            'is_on_sale','is_city', 'shop_goods_type');
        $goods = $goodsModel
            ->where(["goods_id" => $goods_id])
            ->field($fields)->find();
        if ( !$goods || !$goods['is_on_sale'] )
        {
            return array('status' => -10, 'msg' => '商品失效，请重新下单！'.$goods_id, 'result' => '');
        }

        if ($goods) {
            $address = M('UserAddress')->where([
                "address_id" => $address_id
            ])->find();
            if(!$address){
                return array('status' => -11, 'msg' => '收货地址不存在！', 'result' => '');
            }

            $latitude = -1;
            $longitude = -1;
            if($address){
                $latitude = $address['latitude'];
                $longitude = $address['longitude'];
            }

            $shop_goods = M('shop_goods')->alias('shop_goods')
                ->field('shop_goods.*')
                ->join('ln_shop as shop on shop_goods.shop_id = shop.id')
                ->where(array('shop_goods.goods_id'=>$goods_id, 'shop_goods.shop_on_sale'=>1, 'shop_goods.store_count'=>array('egt', $goods_num), 'shop.is_open'=>1))
                ->select();

            if($shop_goods){
                $shop_ids = array();
                //$goods_store = 0;
                $shop_goods_array = array();
                foreach($shop_goods as $val){
                    $shop_ids[] = $val['shop_id'];
                    //$goods_store += $val['store_count'];
                    $shop_goods_array[$val['shop_id']] = $val;
                }
                /*if($goods_store < $goods_num){
                    return array('status' => -12, 'msg' => '库存不足！', 'result' => '');
                }*/
                $shop_ids = get_arr_column($shop_goods, 'shop_id');
                $fields = array('id as shop_id', 'latitude', 'longitude', 'is_auto_confirm');
                $order = 'id desc';
                if($latitude != -1 && $longitude != -1 ){
                    $fields[] = '(2 * 6378.137* ASIN(SQRT(POW(SIN(3.1415926535898*('.$latitude.'-latitude)/360),2)+COS(3.1415926535898*'.$latitude.'/180)* COS(latitude * 3.1415926535898/180)*POW(SIN(3.1415926535898*('.$longitude.'-longitude)/360),2))))*1000 as juli';
                    $order .= ' , juli asc';
                }else{
                    $fields[] = '0 as juli';
                }
                $shop_where['is_open'] = 1;
                $shop_where['id'] = array('in', $shop_ids);
                $shop_info = M('shop')->field($fields)
                    ->where($shop_where)
                    ->order($order)
                    ->find();

                if($goods['is_city'] == 1){
                    $dada_distance = tpCache('shopping.dd_distance');
                    if($shop_info['juli'] > bcmul($dada_distance, 1000, 2)){
                        return array('status' => -11, 'msg' => '商品超出配送范围！', 'result' => '');
                    }
                }

                //$flag_goods_num = $goods_num;
                $return_data = array();

                $all_exchange_integral = 0;
                $promPrice = calcGoodsPrice( $goods);
                $price = $promPrice['price'];

                $prom_price = $price;  // 活动价
                $member_goods_price = $price;

                $total_price_sum = 0;
                $post_fee_sum = 0;
                $cut_fee_sum = 0;
                $market_cut_fee_sum = 0;

                if( $promPrice['is_prom'] )
                {
                    $prom_type = $goods['prom_type'];    // 0 普通订单, 3 促销优惠
                    $prom_id = $goods['prom_id'];      // 活动id
                }else{
                    $prom_type = 0;    // 0 普通订单, 3 促销优惠
                    $prom_id = 0;      // 活动id
                }

                //foreach($shop_list as $val){
                    //$shop_info = $val;
                $goods_info = $shop_goods_array[$shop_info['shop_id']];
                $shop_info['shop_head_img'] = parseMediaUrl($shop_info['shop_head_img']);
                    //if($flag_goods_num <= $shop_goods_array[$val['shop_id']]['store_count']){
                $goods_info['goods_num'] = $goods_num;
                $return_data[] = array(
                    'shop_id' => $shop_info['shop_id'],
                    'shop_name' => $shop_info['shop_name'],
                    'shop_head_img' => $shop_info['shop_head_img'],
                    'shop_info'=>$shop_info,
                    'selected'=>1,
                    'cartList'=>array($goods_info),
                );
                        //break;
                   // }else{
                   //     $goods_info['goods_num'] = $shop_goods_array[$val['shop_id']]['store_count'];
                   //     $return_data[] = array(
                           // 'shop_id' => $val['shop_id'],
                           // 'shop_name' => $val['shop_name'],
                          //  'shop_head_img' => parseMediaUrl($val['shop_head_img']),
                          //  'shop_info'=>$shop_info,
                          //  'selected'=>1,
                          //  'cartList'=>array($goods_info),
                        //);
                        //$flag_goods_num -= $shop_goods_array[$val['shop_id']]['store_count'];
                   // }
                //}

                M()->startTrans(); // 开启事务
                $main_order_sn = 'M' . $this->_createOrderSN();

                $add_data['user_id'] = $user_id;
                $add_data['add_time'] = time();
                $add_data['parent_sn'] = $main_order_sn;
                $add_data['consignee'] = $address['consignee'];
                $add_data['mobile'] = $address['mobile'];
                $add_data['zipcode'] = $address['zipcode'];
                $add_data['province'] = $address['province'];
                $add_data['city'] = $address['city'];
                $add_data['district'] = $address['district'];
                $add_data['twom'] = $address['twom'];
                $add_data['address'] = $address['address'];
                $add_data['receiver_lng'] = $address['longitude'];
                $add_data['receiver_lat'] = $address['latitude'];
                $orderGoodsModel = M('order_goods');
                foreach($return_data as &$val){
                    $total_price = 0;
                    $weight = 0;
                    $cut_fee = 0;
                    $anum = 0;
                    $market_cut_fee = 0;
                    $integral_points = 0;

                    foreach($val['cartList'] as &$val2){

                        $val2['goods_price'] =  $goods['shop_price'];
                        $integral_points += $goods['exchange_integral'] * $val2['goods_num'];
                        $all_exchange_integral += $integral_points;
                        $val2['member_goods_price'] = $price;
                        $val2['prom_type'] = $prom_type;
                        $val2['prom_id'] = $prom_id;
                        $val2['prom_price'] = $prom_price;
                        $val2['goods_sn'] = $goods['goods_sn'];
                        $val2['goods_name'] = $goods['name'];
                        $val2['market_price'] = $goods['market_price'];
                        $val2['goods_fee'] = (($val2['goods_num'] * $member_goods_price) * 100) / 100;
                        $total_price += $val2['goods_fee'];
                        $cut_fee += ((($goods['shop_price'] - $member_goods_price) * $val2['goods_num']) *100)/100;
                        if( !$goods['is_free_shipping'] )
                        {
                            $weight += $goods['weight'] * $val2['goods_num'] ;
                        }
                        $anum += $val2['goods_num'];
                        $market_cut_fee += ((($goods['market_price'] - $member_goods_price) * $val2['goods_num']) *100)/100;
                    }

                    if($goods['shop_goods_type'] == 0) {
                        $post_fee = \Common\Logic\FeeLogic::getPostFeeNew($val['shop_id'], $weight, $total_price, $shop_info['juli']);
                    }else{
                        $post_fee = 0;
                    }

                    $val['total_price'] = array(
                        'total_fee' => $total_price,
                        'post_fee' => $post_fee,
                        'cut_fee' => $cut_fee,
                        'num' => $anum,
                        'market_cut_fee' => $market_cut_fee
                    );


                    $total_price_sum += $total_price;
                    $post_fee_sum += $post_fee;
                    $cut_fee_sum += $cut_fee;
                    $market_cut_fee_sum += $market_cut_fee;
                }


                $point_rate = tpCache('shopping.point_rate');
                $total_amount = bcadd($total_price_sum, $post_fee_sum, 2);;
                if ( bccomp($total_amount,0,2) < 1  )
                {
                    $total_amount = 0;
                }
                $order_amount_point = intval( $total_amount * $point_rate );
                $all_pay_point = $all_exchange_integral > $order_amount_point ? $order_amount_point : $all_exchange_integral;  //订单最高允许使用积分

                if( $pay_points === true )
                {
                    $pay_points = $all_pay_point;
                }

                if ($pay_points > 0) {
                    if ($pay_points > $all_exchange_integral) {
                        $pay_points = $all_exchange_integral;
                    }
                } else {
                    $pay_points = 0;
                }
                $userInfo = M('users')->field('pay_points')->where(array('user_id'=>$user_id))->find();
                if ($pay_points > 0 && $userInfo && $pay_points > $userInfo['pay_points']) {
                    return array('status' => -5, 'msg' => "积分余额不足，你的账户可用积分为:" . $userInfo['pay_points'], 'result' => ''); // 返回结果状态
                }

                $pay_points = ($pay_points / $point_rate ); // 积分支付 100 积分等于 1块钱
                $pay_points = ($pay_points > $total_amount) ? $total_amount : $pay_points; // 假设应付 1块钱 而用户输入了 200 积分 2块钱, 那么就让 $pay_points = 1块钱 等同于强制让用户输入1块钱
                $order_amount = bcsub( $total_amount, $pay_points,2 ); //  积分抵消应付金额

                // 查询优惠券信息
                if($coupon_id != 0 ){
                    $Model = new \Think\Model(); // 找出这个用户的优惠券 没过期的  并且 订单金额达到 condition 优惠券指定标准的
                    $sql = "select c1.name,c1.money,c1.condition, c2.* from ln_coupon as c1 inner join ln_coupon_list as c2  on c2.cid = c1.id and c1.type in(0,1,2,3,5) and order_id = 0  where c2.id = {$coupon_id}  and c2.uid = {$user_id}  and " . time() . " < c1.use_end_time and c1.use_start_time < " . time();
                    $couponList = $Model->query($sql);
                    if(count($couponList) > 0){
                        $couponData = $couponList[0];
                        // 不同类型处理
                        if($couponData['type'] == 5){// 商品全额抵扣
                            $coupon_price = $order_amount;
                            $order_amount = 0;
                        }
                    }
                }

                $val_1 = $return_data[0];
                $add_data['integral_money'] = 0;
                $add_data['integral'] = 0;
                $add_data['goods_price'] = $price;
                $add_data['user_note'] = $user_note ? $user_note[0] : '';
                $add_data['order_sn'] = 'S' . $this->_createOrderSN();
                $add_data['shipping_price'] = $post_fee;
                $add_data['shop_id'] = $val_1['shop_id'];
                //$add_data['order_status'] = $val_1['shop_info']['is_auto_confirm'];   //自动接单

                $add_data['total_amount'] = $total_amount;
                $add_data['order_amount'] = $order_amount;
                $add_data['total_buy_number'] = $anum;
                $add_data['order_type'] = $goods['shop_goods_type'] == 0 ? 1 : 2;
                $sOrderId = M('order')->data($add_data)->add();
                if ($sOrderId <= 0) {
                    M()->rollback(); // 事务回滚
                    $this->returnInfo(0, '子订单表写入失败, 未知原因');
                }
                add_shop_message($add_data['shop_id'], '新的订单', '您有新的订单，请前往查看处理',1, $sOrderId);

                $logResult = order_log($add_data['order_sn'], '', '提交订单', 1);
                if ($logResult === false) {
                    M()->rollback(); // 事务回滚
                    return array('status' => -13, 'msg' => '订单日志写入失败, 未知原因！', 'result' => '');
                }

                $order_goods_data = [];
                $order_goods_data['order_id'] = $sOrderId;
                $order_goods_data['order_sn'] = $add_data['order_sn'];
                $order_goods_data['user_id'] = $user_id;
                $order_goods_data['goods_id'] = $goods_id;
                $order_goods_data['goods_name'] = $goods['goods_name'];

                foreach($val_1['cartList'] as &$val3){
                    $order_goods_data['goods_price'] =  $val3['goods_price'];
                    $order_goods_data['member_goods_price'] = $val3['member_goods_price'] > 0 ? $val3['member_goods_price'] : $order_goods_data['goods_price'];
                    $order_goods_data['goods_num'] = $val3['goods_num'];
                    $goodsOrderId = $orderGoodsModel->data($order_goods_data)->add();
                    if ($goodsOrderId <= 0) {
                        M()->rollback(); // 事务回滚
                        return array('status' => -14, 'msg' => '订单商品表写入失败, 未知原因！', 'result' => '');
                    }
                    $sonStorge = $this->decreaseShopGoodsNumber($add_data['order_sn']);
                    if ($sonStorge === false) {
                        M()->rollback(); // 事务回滚
                        return array('status' => -14, 'msg' => '库存处理失败！', 'result' => '');
                    }
                    //写入订单日志
                    order_log($add_data['order_sn'], '', '减少库存成功', 1);
                }


                $main_order_data = array();
                $main_order_data['add_time'] = time();
                $main_order_data['order_sn'] = $main_order_sn;
                $main_order_data['integral_money'] = $pay_points;
                $main_order_data['total_buy_number'] = $goods_num;
                $main_order_data['total_amount'] = $total_amount;
                $main_order_data['order_amount'] = $order_amount;
                $main_order_data['shipping_price'] = $post_fee_sum;
                $main_order_data['integral'] = $all_pay_point;
                $main_order_data['goods_price'] = $total_price_sum;
                $main_order_data['real_pay_amount'] = $order_amount;
                $main_order_data['user_id'] = $user_id;

                $mainOrderId = M('order')->data($main_order_data)->add();
                if ($mainOrderId <= 0) {
                    M()->rollback(); // 事务回滚
                    return array('status' => -14, 'msg' => '主订单表写入失败, 未知原因！', 'result' => '');
                }
                session_start();
                $_SESSION["order_sn"] = $main_order_sn;
                #如果使用积分，先扣
                if ($pay_points) {

                    if( $pay_points === true )
                    {
                        $pay_points = $all_pay_point;
                    }

                    if ($all_pay_point > $pay_points) {
                        return array('status'=>-15, 'msg'=>'无足够积分支付抵扣', 'result'=>'');
                    }

                    if (!$userInfo || $userInfo['pay_points'] < $pay_points) {
                        M()->rollback();
                        return array('status'=>-16, 'msg'=>'积分余额不足', 'result'=>'');
                    }

                    $log = accountLog($user_id, 0, $all_pay_point, '下单抵扣' . $main_order_sn, 0, $mainOrderId, $main_order_sn);

                    if (!$log || !$log['is_success']) {
                        M()->rollback();
                        return array('status'=>-17, 'msg'=>isset($log['message']) ? $log['message'] : '积分抵扣失败!', 'result'=>'');
                    }
                }


                // 消费代金券
                if($coupon_id > 0){
                    $Model = new \Think\Model(); // 找出这个用户的优惠券 没过期的  并且 订单金额达到 condition 优惠券指定标准的
                    $sql = "select c1.name,c1.money,c1.condition, c2.* from ln_coupon as c1 inner join ln_coupon_list as c2  on c2.cid = c1.id and c1.type in(0,1,2,3,5) and order_id = 0  where c2.id = {$coupon_id}  and c2.uid = {$user_id}  and " . time() . " < c1.use_end_time and c1.use_start_time < " . time();
                    $couponList = $Model->query($sql);
                    if(count($couponList) > 0){
                        $couponData = $couponList[0];
                        // 消费
                        M('coupon_list')->where(['id'=>$couponData['id']])->save(['order_id'=>$mainOrderId,'use_time'=>time()]);
                        M('coupon')->where(['id'=>$couponData['cid']])->setInc('use_num');
                    }else{
                        M()->rollback();
                        return array('status' => -1, 'msg' => '代金券消费失败', 'result' => '');
                    }
                }

                if ($main_order_data['order_amount'] == 0)
                {
                    doLog($main_order_data['order_sn'] . "订单应付金额为0", "payorder");
                    update_pay_status($main_order_data['order_sn'], "none","无需支付");
                }
                M()->commit();
                return $main_order_data['order_sn'];
            }else{
                return array('status' => -11, 'msg' => '配送渠道库存不足！', 'result' => '');
            }
        }
    }


    /**
     * 查看购物车的商品数量
     * @param type $user_id
     * $mode 0  返回数组形式  1 直接返回result
     */
    public function cart_count($user_id, $mode = 0)
    {
        $count = M('Cart')->where("user_id = $user_id and selected = 1")->count();
        if ($mode == 1) return $count;

        return array('status' => 1, 'msg' => '', 'result' => $count);
    }

    /**
     * 获取商品团购价
     * 如果商品没有团购活动 则返回 0
     * @param type $attr_id
     * $mode 0  返回数组形式  1 直接返回result
     */
    public function get_group_buy_price($goods_id, $mode = 0)
    {
        $group_buy = M('GroupBuy')->where("goods_id = $goods_id and " . time() . " >= start_time and " . time() . " <= end_time ")->find(); // 找出这个商品                      
        if (empty($group_buy))
            return 0;

        if ($mode == 1) return $group_buy['groupbuy_price'];
        return array('status' => 1, 'msg' => '', 'result' => $group_buy['groupbuy_price']);
    }

    /**
     * 用户登录后 需要对购物车 一些操作
     * @param type $session_id
     * @param type $user_id
     */
    public function login_cart_handle($session_id, $user_id)
    {
        if (empty($session_id) || empty($user_id))
            return false;
        // 登录后将购物车的商品的 user_id 改为当前登录的id            
        M('cart')->where("session_id = '$session_id'")->save(array('user_id' => $user_id));

        $Model = new \Think\Model();
        // 查找购物车两件完全相同的商品
        $cart_id_arr = $Model->query("select id from `__PREFIX__cart` where user_id = $user_id group by  goods_id,spec_key having count(goods_id) > 1");
        if (!empty($cart_id_arr)) {
            $cart_id_arr = get_arr_column($cart_id_arr, 'id');
            $cart_id_str = implode(',', $cart_id_arr);
            M('cart')->delete($cart_id_str); // 删除购物车完全相同的商品
        }
    }

    /**
     * 判断商品是否失效
     * @param $goods_id
     * @param $spec_key
     */
    public function getGoodsStatus($goods_id, $spec_key)
    {
        $status = 1;
        $goods = M("Goods")->where(array('goods_id' => $goods_id, 'is_on_sale' => 1))->find();
        if ($goods) {
            if (!empty($spec_key)) {
                $specGoodsPrice = M("SpecGoodsPrice")->where(array('goods_id' => $goods_id, 'key' => $spec_key))->find();
                if (!$specGoodsPrice) {
                    $status = 0;
                }
            }
        } else {
            $status = 0;
        }
        return $status;
    }




    // 生成订单号
    public function _createOrderSN()
    {
        return date('YmdHis', time()) . '' . $this->randNumber();
    }

    /**
     * 获取随机位数数字
     * @param integer $len 长度
     * @return string
     */
    public function randNumber($len = 4)
    {
        $chars = str_repeat('0123456789', 10);
        $chars = str_shuffle($chars);
        $str = substr($chars, 0, $len);
        return $str;
    }


    /**
     * 减少库存
     * @param $order_sn 要减库存的定单SN
     */
    public function decreaseGoodsNumber($order_sn)
    {
        $where['order_sn'] = $order_sn;
        $orderGoodsData = M('OrderGoods')->field('goods_id, spec_key, goods_num')->where($where)->select();
        foreach ($orderGoodsData as $value) {
            $this->change_goods_storage($value['goods_id'], $value['spec_key'], 0 - $value['goods_num']);
        }
    }

    public function decreaseShopGoodsNumber($order_sn){
        $where['order_goods.order_sn'] = $order_sn;
        $orderGoodsData = M('OrderGoods')->alias('order_goods')
            ->join('ln_order as ord on order_goods.order_sn = ord.order_sn')
            ->field('order_goods.goods_id, order_goods.goods_num, ord.shop_id')
            ->where($where)
            ->select();
        foreach ($orderGoodsData as $value) {
            $this->change_goods_storage_new($value['goods_id'], $value['shop_id'], 0 - $value['goods_num']);
        }
    }

    /**
     * 修改渠道，和系统库存数据，修改系统销售数据
     * @param $goods_id
     * @param $shop_id
     * @param $number
     * @return bool
     */
    public function change_goods_storage_new($goods_id, $shop_id, $number){
        $where['goods_id'] = $goods_id;
        $where['shop_id'] = $shop_id;
        $warning_storage = tpCache('basic.warning_storage');
        $shop_goods_info = M('shop_goods')->field('id, store_count')->where($where)->getField('store_count');
        if($shop_goods_info['store_count'] - $number <= $warning_storage){
            add_shop_message($shop_id, '补货提醒', '商品库存警告',2, $shop_goods_info['id']);
        }
        $is_success_shop_goods = M('shop_goods')->where($where)->setInc('store_count', $number);
        $is_success_goods_count = M('goods')->where(array('goods_id'=>$goods_id))->setInc('store_count', $number);
        $is_success_goods_sales_num = M('goods')->where(array('goods_id'=>$goods_id))->setDec('sales_sum', $number);

        return $is_success_shop_goods !== false && $is_success_goods_count !==false && $is_success_goods_sales_num !== false;
    }

    /**
     * 改变商品规格库存
     * @param int $goods_id 商品id
     * @param string $key 商品规格key值
     * @param int $buy_number 数量 
     */
    public function change_goods_storage($goods_id, $key, $buy_number)
    {
        $where['goods_id'] = $goods_id;
        $where['key'] = $key;
        $res = M('spec_goods_price')->where($where)->setInc('store_count', $buy_number);
        $res = M('goods')->where("goods_id=$goods_id")->setInc('store_count', $buy_number);
        //检测商品是否参加秒杀活动
        $kill = M('flash_sale')->where("goods_id=$goods_id and is_end=0")->find();
        //检测商品是否参加团购
        $group = M('group_buy')->where("goods_id=$goods_id and recommended=1")->find();
        //检测商品是否参加品牌清仓
        $qin = M('prom_goods as pg')->join('ln_goods as gs on gs.prom_id=pg.id')->where("gs.goods_id=$goods_id")->find();
        $where['goods_id'] = $goods_id;
        if (!empty($kill)) {
            $res = M('flash_sale')->where($where)->setInc('goods_num', $buy_number);
        }
        if (!empty($group)) {
            $res = M('group_buy')->where($where)->setInc('goods_num', $buy_number);
        }
        if (!empty($qin)) {
            $res = M('prom_goods as pg')->join('ln_goods as g on g.prom_id=pg.id')->where("g.goods_id=$goods_id")->setInc('goods_num', $buy_number);
        }
        return $res;

    }
}